package com.glodon.paas.account.sdk.sso.web;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Process single sign out
 *
 * @author Don Li
 */
abstract public class AbstractCasSingleSignOutFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        if (isSupported(httpReq)) {
            // invalidate the session
            HttpSession session = httpReq.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            final String url = buildRequestUrl();
            httpResp.sendRedirect(url);
            return;
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

    abstract protected boolean isSupported(HttpServletRequest request);

    /**
     * @return the PAAS service id
     */
    abstract protected String getServiceId();

    /**
     * @return return url after logout
     */
    abstract protected String getReturnTo();

    /**
     * @return the service logout url
     */
    abstract protected String getServiceLogoutUrl();

    private String buildRequestUrl() {
        return getServiceLogoutUrl() + "?service=" + getServiceId() + "&return_to=" + getReturnTo();
    }
}
